package com.dmall.ssm.hystrix;

import com.alibaba.fastjson.JSON;
import com.dmall.ssm.request.UserRequestPara;
import com.dmall.ssm.result.CommonResult;
import com.dmall.ssm.service.UserService;
import com.netflix.hystrix.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UserCommand extends HystrixCommand<CommonResult> {

    private static final Logger log = LoggerFactory.getLogger(UserCommand.class);

    private UserService userService;
    private UserRequestPara para;

    public UserCommand(UserService userService, UserRequestPara para) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("UserGroup"))
                .andCommandKey(HystrixCommandKey.Factory.asKey("UserCommand"))
                .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("UserCommandThreadPool"))
                //超时时间1100毫秒, 略长于dubbo配置, 避免超时间低于dubbo配置
                .andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(3100)));
        this.userService = userService;
        this.para = para;
    }

    @Override
    protected CommonResult run() throws Exception {
        CommonResult result = null;
        try {
            long startTime = System.currentTimeMillis();
            result = userService.testHystrix(para);
            long endTime = System.currentTimeMillis();
            log.info("调用接口结束，耗时[{}]，相应结果result={}", (endTime - startTime), JSON.toJSONString(result));
        } catch (Exception e) {
            result = new CommonResult();
            result.setCode("0001");
            result.setMsg("服务熔断");
        }
        return result;
    }

    @Override
    protected CommonResult getFallback() {
        CommonResult result = new CommonResult();
        result.setCode("0001");
        result.setMsg("Hystrix 熔断");
        return result;
    }
}
